package com.histone.heartbeat.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

@Service
@Slf4j
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String sender;

    /**
     * 发送邮件
     */
    public void sendMail (String sendTo, String subject, String text) throws Exception{
        Long startTime = System.currentTimeMillis();

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,"UTF-8");
        helper.setFrom(sender);
        helper.setTo(sendTo);
        helper.setSubject(subject);
        helper.setText(text, true);

        mailSender.send(mimeMessage);
        log.info("send email to {} successful, take time {}s", sendTo, (System.currentTimeMillis() - startTime)/1000);

    }

}
